# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.User.User import User
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
import logging

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from AppBase import Base


'''

'''
class InfoEdit(Base):

    @view_config(route_name='AppPortraitEditRoute', request_method='POST')
    def AppPortraitEditRoute(self):
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            uploadFile = postParams.getone('image_file')
            input_file = uploadFile.file
            suffix = postParams.getone('suffix')
        except Exception, e:
            log.error(e)

        tmpTokenString = self.calculateToken(tString, tel)

        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        # The file instance
        fileMD5 = HashUtil.getFileMD5(input_file.read())
        fileName = fileMD5 + '.' + suffix
        log.debug('[PORTRAIT][MD5]' + fileMD5)

        # The file path
        file_path = os.path.join('/media/img', suffix, fileMD5[0: 2], fileMD5[2: 4], fileName)
        temp_file_path = file_path + '.tmp'
        input_file.seek(0)
        folderName = file_path[0: file_path.rfind('/') + 1]
        if not os.path.exists(folderName):
            os.makedirs(folderName)

        with open(temp_file_path, 'wb') as output_file:
            shutil.copyfileobj(input_file, output_file)
        os.rename(temp_file_path, file_path)

        updateSQL = '''
            UPDATE user_info SET portrait = %s
                WHERE user_info.tel = %s;
                '''
        resultUpdate = MySqlCRUD.updateImpl(updateSQL, file_path, tel)
        map = {'RetCode': '0', 'message': '更新头像成功!', 'data': file_path}
        jsonStr = json.dumps(map, ensure_ascii=False)
        jsonStr = jsonStr.replace('/media', '/static')
        log.debug(jsonStr)
        return Response(jsonStr)

    @view_config(route_name='AppInforEditRoute', request_method='POST')
    def AppInforEditRoute(self):
        try:
            postParams =  self.request.POST
            tel = postParams.getone('tel')
            tString = postParams.getone('tString')
            eString = postParams.getone('eString')
            tokenString = postParams.getone('tokenString')
            csc = postParams.getone('csc')
            target = postParams.getone('target')
        except Exception, e:
            log.error(e)

        tmpTokenString = self.calculateToken(tString, tel)
        cache = ChecksumCache()
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '请重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)

        tmpCS = cache.getCache(tel)
        if tmpCS <> csc:
            map = {'RetCode': '126', 'message': '流程验证失败!', 'data': '重新提交请求'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return Response(jsonStr)
        #修改手机号码，需要输入新手机号、发送到原手机上的验证码；
        if target == 'TEL':
            newTel = postParams.getone('data1')
            verifyCode = postParams.getone('data2')
            resultTel = self.checkTelAvailable(newTel)
            if not resultTel:
                map = {'RetCode': '121', 'message': '手机号码修改失败!', 'data': '手机号已被使用！'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error(jsonStr)
                return Response(jsonStr)
            else:
                #TODO 之后五行原来是注释的，2015.11.09年修改版本是去掉注释
                checkresult = self.calcSmsCheckSum(tel, verifyCode)
                if checkresult != 200:
                    map = {'RetCode': '121', 'message': '手机号码修改失败!', 'data': 'MOD' + str(checkresult)}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    return Response(jsonStr)
                updateSQL = '''
                    UPDATE user_info SET tel = %s
                    WHERE user_info.tel = %s;
                '''
                resultUpdate = MySqlCRUD.updateImpl(updateSQL, newTel, tel)
                if resultUpdate == 1:
                    map = {'RetCode': '0', 'message': '手机号码修改成功!', 'data': newTel}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    log.debug('[TEL][EDIT]' + jsonStr)
                    return Response(jsonStr)
                else:
                    map = {'RetCode': '121', 'message': '手机号码修改失败!', 'data': ''}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    log.error('[TEL][EDIT]' + jsonStr)
                    return Response(jsonStr)
        #修改密码，需要输入原密码、新密码；
        elif target == 'PASSWORD':
            oldPassword = postParams.getone('data1')
            newPassword = postParams.getone('data2')
            if (not oldPassword) or (not newPassword):
                map = {'RetCode': '122', 'message': '密码修改失败!', 'data': '原密码或新密码为空！'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error('[PASSWORD][EDIT]' + jsonStr)
                return Response(jsonStr)
            if oldPassword == newPassword:
                map = {'RetCode': '122', 'message': '密码修改失败!', 'data': '原密码与新密码相同！'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error('[PASSWORD][EDIT]' + jsonStr)
                return Response(jsonStr)
            resultPW = self.checkPwAvailable(tel, oldPassword)
            if not resultPW:
                map = {'RetCode': '122', 'message': '密码修改失败!', 'data': '原密码错误！'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error('[PASSWORD][EDIT]' + jsonStr)
                return Response(jsonStr)
            else:
                newPasswordDigest = HashUtil.getStringMD5(newPassword)
                updateSQL = '''
                    UPDATE user_info SET `password` = %s, `default` = %s
                    WHERE user_info.tel = %s;
                '''
                resultUpdate = MySqlCRUD.updateImpl(updateSQL, newPasswordDigest, newPassword, tel)
                if resultUpdate == 1:
                    map = {'RetCode': '0', 'message': '密码修改成功!', 'data': ''}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    log.debug('[PASSWORD][EDIT]' + jsonStr)
                    return Response(jsonStr)
                else:
                    map = {'RetCode': '122', 'message': '密码修改失败!', 'data': ''}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    log.error('[PASSWORD][EDIT]' + jsonStr)
                    return Response(jsonStr)
        #修改用户名，需要输入新用户名；
        elif target == 'USERNAME':
            newUsername = postParams.getone('data1')
            updateSQL = '''
                UPDATE user_info SET username = %s
                WHERE user_info.tel = %s;
            '''
            resultUpdate = MySqlCRUD.updateImpl(updateSQL, newUsername, tel)
            if resultUpdate == 1:
                map = {'RetCode': '0', 'message': '用户名修改成功!', 'data': newUsername}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.debug('[USERNAME][EDIT]' + jsonStr)
                return Response(jsonStr)
            else:
                map = {'RetCode': '124', 'message': '用户名修改失败!', 'data': ''}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error('[USERNAME][EDIT]' + jsonStr)
                return Response(jsonStr)
        #修改邮箱，需要输入新邮箱；
        elif target == 'EMAIL':
            newEmail = postParams.getone('data1')
            if not newEmail:
                map = {'RetCode': '125', 'message': '邮箱修改失败!', 'data': '邮箱为空！'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error('[USERNAME][EDIT]' + jsonStr)
                return Response(jsonStr)
            resultEmail = self.checkEmailAvailable(newEmail)
            if not resultEmail:
                map = {'RetCode': '125', 'message': '邮箱修改失败!', 'data': '邮箱已被使用！'}
                jsonStr = json.dumps(map, ensure_ascii=False)
                log.error('[USERNAME][EDIT]' + jsonStr)
                return Response(jsonStr)
            else:
                updateSQL = '''
                    UPDATE user_info SET email = %s
                    WHERE user_info.tel = %s;
                '''
                resultUpdate = MySqlCRUD.updateImpl(updateSQL, newEmail, tel)
                if resultUpdate == 1:
                    map = {'RetCode': '0', 'message': '邮箱修改成功!', 'data': newEmail}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    log.debug('[USERNAME][EDIT]' + jsonStr)
                    return Response(jsonStr)
                else:
                    map = {'RetCode': '125', 'message': '邮箱修改失败!', 'data': ''}
                    jsonStr = json.dumps(map, ensure_ascii=False)
                    log.error('[USERNAME][EDIT]' + jsonStr)
                    return Response(jsonStr)
        else:
            map = {'RetCode': '127', 'message': '无效操作!', 'data': ''}
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error('[USERNAME][EDIT]' + jsonStr)
            return Response(jsonStr)
